package com.zipking.cloud.springbootmybatis.current;

import org.checkerframework.checker.units.qual.K;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class DistributedCache<K, V> {
    private final ConcurrentHashMap<K, V> cacheMap = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<K, Long> expirationMap = new ConcurrentHashMap<>();

    public void put(K key, V value, long ttl) {
        cacheMap.put(key, value);
        expirationMap.put(key, System.currentTimeMillis() + ttl);
        scheduleEviction(key, ttl);
    }

    public V get(K key) {
        Long expirationTime = expirationMap.get(key);
        if (expirationTime == null || expirationTime < System.currentTimeMillis()) {
            cacheMap.remove(key);
            expirationMap.remove(key);
            return null;
        }
        return cacheMap.get(key);
    }

    private void scheduleEviction(final K key, final long ttl) {
        new Thread(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(ttl);
                cacheMap.computeIfPresent(key, (k, v) -> null);
                expirationMap.remove(key);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }

    public static void main(String[] args) {
        DistributedCache<String, String> cache = new DistributedCache<>();
        cache.put("userSession", "sessionData", 5000); // 缓存设置5秒过期

        // 多个线程并发访问缓存
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(() -> {
                String result = cache.get("userSession");
                System.out.println("Thread " + finalI + " retrieved: " + result);
            }).start();
        }
    }
}

